import Request from '../util/luch-request'
import config from "./config.js";

const envFlag = process.env.NODE_ENV;
const baseURL = config[envFlag].BASE_URL;
const timeout = config[envFlag].Timeout;
let timer = null;
let loading = false;

// 全局配置
const http = new Request({
	baseURL,
	header: {
		'content-type': "application/x-www-form-urlencoded;charset=UTF-8"
	},
	timeout
})

// 请求拦截
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	if(timer) {
		clearTimeout(timer);
		timer = null
	}
	// 超过2s显示loading
	timer = setTimeout(() => {
		uni.showLoading({
			mask: true,
			title: '努力加载中 ~'
		})
		loading = true
	}, 2000)
	return config
})

//响应拦截
http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
	if(timer) {
		clearTimeout(timer);
		timer = null
	}
	if(loading) {
		uni.hideLoading();
		loading = false;
	}
	if(response.data.code !== 200) {
		uni.showToast({
			title: response.data.msg || '网络错误, 请稍后再试',
			icon: 'none',
			duration: 3000
		})
		return Promise.reject(response)
	}
	return response.data
}, (response) => { /*  对响应错误做点什么 （statusCode !== 200）*/
	console.log(response)
	if(timer) {
		clearTimeout(timer);
		timer = null
	}
	if(loading) {
		uni.hideLoading();
		loading = false;
	}
	uni.showToast({
		title: response.data.msg || '网络错误, 请稍后再试',
		icon: 'none',
		duration: 3000
	})
	return Promise.reject(response)
})

export default http
